#include "psmonitor.h"
#include <sys/epoll.h>
//#include <cstddef.h>

CPSMonitor::CPSMonitor()
{
	m_fd = epoll_create(128);
}

CPSMonitor::~CPSMonitor()
{
}

bool CPSMonitor::AddMonitor(IPSEvent* p, int events)
{
	struct epoll_event		evt		= {0};

	if(-1 == m_fd || 0 == p || -1 == p->GetEventFd())
	{
		return false;
	}

	evt.events = events;
	evt.data.ptr = p;
	return (0 == epoll_ctl(m_fd, EPOLL_CTL_ADD, p->GetEventFd(), &evt));
}

bool CPSMonitor::DelMonitor(IPSEvent* p)
{
	struct epoll_event		evt		= {0};

	if(0 == p || -1 == p->GetEventFd())
	{
		return false;
	}

	return (0 == epoll_ctl(m_fd, EPOLL_CTL_ADD, p->GetEventFd(), &evt));
}

bool CPSMonitor::ModMonitor(IPSEvent* p, int events)
{
	struct epoll_event		evt		= {0};

	if(-1 == m_fd || 0 == p || -1 == p->GetEventFd())
	{
		return false;
	}

	evt.events = events;
	evt.data.ptr = p;
	return (0 == epoll_ctl(m_fd, EPOLL_CTL_MOD, p->GetEventFd(), &evt));
}

void CPSMonitor::Run(void)
{
	struct epoll_event		evts[1024]		= {0};
	int						nums;

	while(true)
	{
		nums = epoll_wait(m_fd, evts, sizeof(evts) / sizeof(struct epoll_event), -1);
		if(nums <= 0)
		{
			break;
		}

		for(int i = 0; i < nums; i++)
		{
			IPSEvent*		p	= (IPSEvent*)evts[i].data.ptr;

			if(EPOLLIN == evts[i].events)
			{
				p->OnEventIn();
			}
			else if(EPOLLOUT == evts[i].events)
			{
				p->OnEventOut();
			}
			else if(EPOLLPRI == evts[i].events)
			{
				p->OnEventPri();
			}
			else
			{
				DelMonitor(p);
				p->OnEventError();
			}
		}
	}

}
